
package ift605.jade.part1Example;

import jade.core.Agent;
import jade.domain.FIPAAgentManagement.*;
import jade.domain.DFService;
import jade.core.behaviours.CyclicBehaviour;
import jade.lang.acl.ACLMessage;
import jade.lang.acl.MessageTemplate;


/**
 * This agent is based on the ThanksAgent example, described as below
 * 
 * This agent has the following functionality: 
 * <ul>
 * <li> registers with the DF
 * <li> creates a list of agents
 * <li> each of this new agents registers with the DF
 * <li> the father agent sends a message of greeting to each of them
 * <li> it waits for an answer to the greeting
 * <li> it thanks the agents that have answered 
 * </ul>
 * @author Fabio Bellifemine, TILab
 * @version $Date: 2009-07-01 15:43:58 +0200 (mer, 01 lug 2009) $ $Revision: 6151 $
 **/
public class GreetingsAgent extends Agent {

	public final static String GREETINGS = "That was the worst throw ever. Of all time.";
	public final static String THANKS = "Not my fault. A wall got in my way.";

	protected void setup() {
		System.out.println("Creation of :: " + getLocalName());

		addBehaviour(new CyclicBehaviour(this) {
			public void action() {
				ACLMessage msg = receive(MessageTemplate.MatchPerformative(ACLMessage.INFORM));
				if (msg != null) {
					if (THANKS.equalsIgnoreCase(msg.getContent())) {
						System.out.println(myAgent.getLocalName()+" received a message from "+msg.getSender().getLocalName() + " : " + msg.getContent()); 
						
						myAgent.doDelete();
					}
					else {
						System.out.println(myAgent.getLocalName()+" Unexpected message received from "+msg.getSender().getLocalName()); 
					}					
				}
				else {
					// if no message is arrived, block the behaviour
					block();
				}
			}
		});
		
		addBehaviour(new CyclicBehaviour(this) {
			public void action() {
				try
				{
					DFAgentDescription dfd = new DFAgentDescription();
					ServiceDescription sd = new ServiceDescription();
					sd.setType(THANKS);
					sd.setName(THANKS);
					
					dfd.addServices(sd);
					
					DFAgentDescription[] desc = DFService.search(myAgent, dfd);
	
					for(DFAgentDescription agent : desc)
					{
						// send them a GREETINGS message
						ACLMessage msg = new ACLMessage(ACLMessage.INFORM);
						msg.setContent(GREETINGS);
		
						msg.addReceiver(agent.getName());
		
						send(msg);
					}
				}
				catch(Exception e)
				{
					e.printStackTrace();
				}
			}
		});
	}

	protected void takeDown() {
		System.out.println("Death of :: " + getLocalName());
	}
}
